package com.hardydou.system.service.impl;

import com.hardydou.common.result.Code;
import com.hardydou.common.result.ResultAssert;
import com.hardydou.system.mapper.SystemDeptMapper;
import com.hardydou.system.model.SystemDept;
import com.hardydou.system.service.ISystemDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020-03-10
 * @Copyright ：Hardydou.com
 */
@Service
public class SystemDeptServiceImpl implements ISystemDeptService {

    @Autowired
    private SystemDeptMapper deptMapper;


    @Override
    public SystemDept findById(Long deptId) {
        return deptMapper.selectByPrimaryKey(deptId);
    }

    @Override
    public List<SystemDept> findAll(Map params) {
        return deptMapper.findAll(params);
    }

    @Override
    public List<SystemDept> findByids(long[] deptIds) {
        return deptMapper.findByids(deptIds);
    }

    @Override
    public int addDept(SystemDept dept) {
        dept.setCtime(new Date());
        dept.setUtime(dept.getCtime());
        //ancestors
        SystemDept parent = deptMapper.selectByPrimaryKey(dept.getParentId());
        if (parent != null) {
            dept.setAncestors(parent.getDeptId() + "," + parent.getAncestors());
        }
        return deptMapper.insert(dept);
    }

    @Override
    public int update(SystemDept dept) {
        SystemDept self = deptMapper.selectByPrimaryKey(dept.getDeptId());
        //祖先需要改变
        if (!self.getParentId().equals(dept.getParentId())) {
            SystemDept parent = deptMapper.selectByPrimaryKey(dept.getParentId());
            if (parent != null) {
                dept.setAncestors(parent.getDeptId() + "," + parent.getAncestors());
            }
            deptMapper.updateAncestors(self.getAncestors(), dept.getAncestors());
        }
        return deptMapper.updateByPrimaryKeySelective(dept);
    }

    @Override
    public void deleteByDeptId(Long deptId) {
        int deptCount = deptMapper.checkDeptExitDept(deptId);
        ResultAssert.isTrue(deptCount == 0, Code.DEPT_DEL_HAS_DEPT);
        int userCount = deptMapper.checkDeptExistUser(deptId);
        ResultAssert.isTrue(userCount == 0, Code.DEPT_DEL_HAS_USER);
        int r = deptMapper.deleteByPrimaryKey(deptId);
        ResultAssert.isTrue(r == 1, Code.DEPT_DEL_ERROR);
    }

}
